package com.warrior.service;

import com.warrior.entity.AdminUser;
import com.warrior.respository.IAdminRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 后台管理的service层
 * Created by shawn on 2017/4/25.
 */
@Service
public class AdminService {

    @Autowired
    private IAdminRepository adminRepository;

    /**
     * 保存一个管理员
     * @param adminUser 管理员对象
     * @return 返回一个管路员对象
     */
    @Transactional
    public AdminUser saveAdminUser(AdminUser adminUser){
         return this.adminRepository.save(adminUser);
    }

    /**
     * 根据id找到一个管理员信息
     * @param adminId 管理员id
     * @return 返回一个管理员对象
     */
    @Transactional
    public AdminUser findAdminUserById(String adminId){
        return this.adminRepository.findOne(adminId);
    }

    /**
     * 根据用户名查找管理员用户
     * @param userName 用户名
     * @return
     */
    @Transactional
    public AdminUser findAdminUserByName(String userName){
        return this.adminRepository.findAdminUserByUserName(userName);
    }


    /**
     * 验证登录
     * @param userName 用户名
     * @param password 密码
     * @return boolEAN
     */
    public boolean validateAdminLogin(String userName,String password){
        boolean flag = false;
        AdminUser user = this.findAdminUserByName(userName);
        if (null != user) {
            //只有状态为未锁定的用户才可以登陆
            if (-1 != user.getUserStatus()) {
                if (null != user.getPassword() && password.equals(user.getPassword())) {
                    flag = true;
                }
            }
        }
        return flag;
    }

    /**
     * 删除一个管理员用户
     * @param userId 用户id
     */
    @Transactional
    public void deleteAdminUser(String userId){
        this.adminRepository.delete(userId);
    }

    @Transactional
    public Page<AdminUser> listAllAdminUser(int page,int size,String orderType){
        Sort sort = new Sort(Sort.Direction.ASC, "createdAt");
        if ("desc".equals(orderType)) {
            sort = new Sort(Sort.Direction.DESC, "createdAt");
        }
        //设置分页参数
        Pageable pageable = new PageRequest(page, (size <= 0) ? 3 : size, sort);
        Page<AdminUser> adminUsers = this.adminRepository.findAll(pageable);
        return adminUsers;
    }



}
